﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.Common;
using Client.DAL;
using Models;
using Prism.Mvvm;
using Prism.Commands;
using System.Windows.Controls;
using Taxhui.Utils.CryptUtils;

namespace Client.ViewModels
{
    public class EditPassViewModel : BindableBase
    {
        #region 命令

        public DelegateCommand<object[]> EditPassCommand { get; private set; }

        #endregion 命令

        #region 构造函数

        public EditPassViewModel()
        {
            EditPassCommand = new DelegateCommand<object[]>(EditPass);
        }

        #endregion 构造函数

        #region 方法

        private StateModel editState;

        private async void EditPass(object[] obj)
        {
            var dc = GetParam(obj);
            if (dc["oldPassBox"] == null || dc["newPassBox"] == null || dc["confirmPassBox"] == null)
                return;
            string oldPass = dc["oldPassBox"];
            string nPass = dc["newPassBox"];
            string cPass = dc["confirmPassBox"];
            if (dc["newPassBox"] != dc["confirmPassBox"])
            {
                Comm.ShowErr("新密码与确认密码不相同", "修改密码");
                return;
            }
            editState = new StateModel { CurStep = Steps.Send };
            UserSrv.EditPass(EditPassCallback, MD5Crypt.MD32Crypt(dc["oldPassBox"]), MD5Crypt.MD32Crypt(dc["newPassBox"]), Comm.UserInfo.Id);
            await editState.CheckState(10);
            if (editState.CurStep == Steps.Succ)
                Comm.ShowErr("修改成功！", "修改密码", Panuon.UI.Silver.MessageBoxIcon.Success);
            else
                Comm.ShowErr(editState.ErrStr, "修改密码");
        }

        private Dictionary<string, string> GetParam(object[] obj)
        {
            Dictionary<string, string> dc = new Dictionary<string, string>();
            foreach (var item in obj)
            {
                if (item is PasswordBox p)
                    dc[p.Name] = p.Password;
            }
            return dc;
        }

        private void EditPassCallback(RetModel rm)
        {
            if (editState.CurStep != Steps.Send) return;
            editState.RM = rm;
            editState.CurStep = rm.Success ? Steps.Succ : Steps.Fail;
        }

        #endregion 方法
    }
}